import 'dart:async';
import 'dart:io';

import 'package:demo/pages.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:tuple/tuple.dart';
import 'package:url_launcher/url_launcher.dart';

import 'general_router.dart';
import 'i_router.dart';


class Routers {
  Routers._();

  static final Routers _instance = Routers._();

  final GlobalKey<NavigatorState> _navigatorKey = GlobalKey<NavigatorState>(debugLabel: 'Routers');

  static GlobalKey<NavigatorState> get navigatorKey => _instance._navigatorKey;

  static BuildContext get navigatorContext => _instance._navigatorKey.currentState!.context;

  static final router = FluroRouter();
  static final List<IRouter> routerList = [];
  static Route<dynamic>? curRoute;

  static void initRouters() {
    /// 指定路由跳转错误返回页
    // router.notFoundHandler = Handler(
    //     handlerFunc: (BuildContext? context, Map<String, List<String>> params) {
    //   return BrowserPage();
    // });

    routerList.add(GeneralRouter());
    for (var element in routerList) {
      element.define(router);
    }
  }

  static Future push(BuildContext context, String path,
      {TransitionType transition = TransitionType.native, bool replace = false, bool clearStack = false, Object? arguments, bool opaque = true}) {
    return router.navigateTo(context, path,
        opaque: opaque, replace: replace, clearStack: clearStack, transition: transition, routeSettings: RouteSettings(arguments: arguments));
  }

  static Future pushTransparent(BuildContext context, String path,
      {TransitionType transition = TransitionType.none, bool replace = false, bool clearStack = false, Object? arguments}) {
    if (path == Pages.paymentVirtual && Routers.isPageOpen(Pages.paymentVirtual)) {
      return completerFuture();
    }
    return router
        .navigateTo(context, path,
            opaque: false, replace: replace, clearStack: clearStack, transition: transition, routeSettings: RouteSettings(arguments: arguments))
        .catchError((dynamic error) {
      debugPrint('$error');
    });
  }

  static void pop(BuildContext context, [dynamic arguments]) {
    debugPrint("pop--context:$context");
    router.pop(context, arguments);
  }

  static void exitApp(BuildContext context) {
    Routers.pop(context);
    exit(0);
  }

  static void unfocus() {
    FocusManager.instance.primaryFocus?.unfocus();
  }

  static bool isPageOpen(String routeName) {
    return curRoute?.settings.name == routeName;
  }

  static Future completerFuture() {
    Completer completer = Completer();
    Future future = completer.future;
    completer.complete();
    return future;
  }

}
